/*-----------------------------------------------------------------------------------
 *
 * 프로그램명	: BoardDAO.java
 * Version		: 1.0
 * 작성일 		: 2006-08-16
 * 작성자		:
 * 수정일 		:
 * 수정자		:
 * 설명		 	:
 * 기능		 	:
 *
 * Copyright (c) 2000 by H&H  All Rights Reserved.
 *
-------------------------------------------------------------------------------------*/
package com.welfare.board;

import java.io.*;

import java.util.*;
import java.sql.*;

import com.zll.framework.conf.Configuration;
import com.zll.framework.db.DBManager;
import com.zll.framework.model.HashList;
import com.zll.framework.util.StringUtil;


public class BoardDAO
{
	public final int LINE_PER_PAGE	= 15;

	public int getTotalPage(int totalCount) {
		return ((totalCount - 1) / this.LINE_PER_PAGE) + 1;
	}

	public HashList selectBoardInfo(HashMap infos) throws Exception
	{
        return DBManager.executeQuery("/board.xml", "select_board_info", infos);
	}

	public HashList selectWordList(HashMap infos) throws Exception
	{
		int currPage	= Integer.parseInt((String)infos.get("curr_page"));
		int startNum	= (currPage - 1) * this.LINE_PER_PAGE;
		int endNum		= this.LINE_PER_PAGE;

		infos.put("start_num",	new Integer(startNum));
		infos.put("end_num",	new Integer(endNum));

		return DBManager.executeQuery("/board.xml", "select_word_list", infos);
	}

	public HashList selectWordInfo(HashMap infos) throws Exception
	{
        return DBManager.executeQuery("/board.xml", "select_word_info", infos);
	}

	public int selectWordSort(HashMap infos) throws Exception {
        return DBManager.executeQuery("/board.xml", "select_word_sort", infos).getInt("sort", 0);
	}

	public int selectWordCount(HashMap infos) throws Exception {
        return DBManager.executeQuery("/board.xml", "select_word_count", infos).getInt("word_count",0);
	}

	public String selectWordNum(String board_id) throws Exception
	{
		HashMap infos = new HashMap();
		infos.put("board_id",	board_id);
        HashList list = DBManager.executeQuery("/board.xml", "select_word_num", infos);
		return StringUtil.nvl(list.get("word_num",0));
	}


	public HashList selectCommentList(HashMap infos) throws Exception
	{
        return DBManager.executeQuery("/board.xml", "select_comment_list", infos);
	}

	public HashList selectCommentInfo(HashMap infos) throws Exception
	{
        return DBManager.executeQuery("/board.xml", "select_comment_info", infos);
	}




    /**
	 * 게시글 저장
	 *
	 * @param	infos
	 * @return	boolean
	 */
	public void saveWord(HashMap infos) throws Exception
    {
		Connection conn = null;

        try
		{
			conn = DBManager.getConnection();

			String job_type = StringUtil.nvl(infos.get("job_type"));

	    	if (job_type.equals("C")) {
	    		DBManager.executeUpdate("/board.xml", "insert_word", infos);
	       	}
	    	else if (job_type.equals("R")) {
	    		DBManager.executeUpdate("/board.xml", "update_word_sort", infos);
	    		DBManager.executeUpdate("/board.xml", "insert_word", infos);
	    	}
	       	else if (job_type.equals("U")) {
	       		DBManager.executeUpdate("/board.xml", "update_word", infos);
	       	}
	       	else if (job_type.equals("D")) {
	       		DBManager.executeUpdate("/board.xml", "delete_word", infos);
	        }
	        else if (job_type.equals("UC")) {
	        	DBManager.executeUpdate("/board.xml", "update_word_count", infos);
	        }

	    	conn.commit();
	    }
	    catch(Exception e)
	    {
	    	conn.rollback();
		}
	    finally
	    {
	    	DBManager.closeConnection(conn);
		}
    }



    /**
	 * 댓글 저장
	 *
	 * @param	infos
	 * @return	boolean
	 */
	public void saveComment(HashMap infos) throws Exception
    {
		Connection conn = null;

        try
		{
			conn = DBManager.getConnection();

		   if ("C".equals(infos.get("job_type"))) {
	    		DBManager.executeUpdate("/board.xml", "insert_comment", infos, conn);
	       	}
	       	else if ("U".equals(infos.get("job_type")))	{
	       		DBManager.executeUpdate("/board.xml", "update_comment", infos, conn);
	       	}
	       	else if ("D".equals(infos.get("job_type"))) {
	       		DBManager.executeUpdate("/board.xml", "delete_comment", infos, conn);
	        }

			conn.commit();
	    }
	    catch(Exception e)
	    {
	    	conn.rollback();
		}
	    finally
	    {
	    	DBManager.closeConnection(conn);
		}
    }



	public static void setPaging(String xml, String sql, HashMap infos) throws Exception {
		if (infos.get("curr_page") == null) {
			infos.put("start_num",	0);
			infos.put("end_num",	Integer.parseInt(StringUtil.nvl(infos.get("end_num"),"1")));
		}
		else {
			int currPage	= Integer.parseInt((String)infos.get("curr_page"));
			int startNum	= (currPage - 1) * Configuration.LINE_PER_PAGE;
			int endNum		= Configuration.LINE_PER_PAGE;

			infos.put("start_num",	new Integer(startNum));
			infos.put("end_num",	new Integer(endNum));
			infos.put("total_count", DBManager.executeQuery(xml, sql, infos).getInt("total_count", 0));
		}
	}


	/**
     * curPage : 현제페이지
     * totalCount : 젠체 게시물수
     * blockCount : 한 페이지의 게시물의 수
     * blockPage : 한화면에 보여질 페이지의 수
     * */
    public static String getPageHtml(HashMap infos, String curUrl) {

   	 	int curPage = new Integer((String)infos.get("curr_page"));	//vo.getCurPage();
   	 	int totalCount = (Integer)infos.get("total_count");	//vo.getTotCount();
   	 	int blockCount = Configuration.LINE_PER_PAGE;	// vo.getPageSize();
   	 	int blockPage = Configuration.PAGE_SIZE;	//vo.getSetPage();
   	 	int startCount = 0;
   	 	int endCount = 0;


   	 	StringBuffer pagingHtml = new StringBuffer();

        // 전체 페이지 수 //Math.ceil 올림
        int totalPage = (int) Math.ceil((double) totalCount / blockCount);
        if (totalPage == 0) {
            totalPage = 1;
        }

       // 연산에 오류가 날수도 있기때문에 오류 보정
        // 현재 페이지가 전체 페이지 수보다 크면 전체 페이지 수로 설정
        if (curPage > totalPage) {
            curPage = totalPage;
        }

       // 현재 페이지의 처음과  마지막 글의 번호 가져오기
        startCount = (curPage - 1) * blockCount + 1;
        endCount = curPage * blockCount;

       // 시작페이지와 마지막페이지 값 구하기
       int startPage = (int) ((curPage - 1) / blockPage) * blockPage + 1;
        int endPage = startPage + blockPage - 1;

       // 연산에 오류가 날수도 있기때문에 오류 보정
        // 마지막페이지가 전체페이지수보다 크면 전체페이지 수로 설정하기
        if (endPage > totalPage) {
            endPage = totalPage;
        }

       // 실제 HTML을 만드는 부분
        // 이전 block 페이지

        pagingHtml = new StringBuffer();

        pagingHtml.append("<table border='0' cellspacing='0' cellpadding='0'>\n<tr>");
        if (curPage > blockPage) {
       	 if (curUrl.indexOf("?") > -1) {
       		 pagingHtml.append("<td class='pagenum_prev'><a href=\""+ curUrl +"&s_curr_page=" + (startPage - 1) + "\">");
       	 } else {
       		 pagingHtml.append("<td class='pagenum_prev'><a href=\""+ curUrl +"?s_curr_page=" + (startPage - 1) + "\">");
       	 }
            pagingHtml.append("<img src='/images/sub/btn_prev.gif' width='18' height='17' border='0' align='absmiddle' />");
            pagingHtml.append("</a></td>");
        }
        //pagingHtml.append("&nbsp;|&nbsp;");

       // 페이지번호, 현재 페이지는 빨간색으로 강조하고 링크를 제거.
        for (int i = startPage; i <= endPage; i++) {
            if (i > totalPage) {
                break;
            }
            if (i == curPage) {
                pagingHtml.append("<td class='pagenum_now'>");
                pagingHtml.append(i);
                pagingHtml.append("</td>");
            } else {
	        	 if (curUrl.indexOf("?") > -1) {
	        		 pagingHtml.append("<td class='pagenum'><a href=\""+ curUrl +"&s_curr_page=");
	        	 } else {
	        		 pagingHtml.append("<td class='pagenum'><a href=\""+ curUrl +"?s_curr_page=");
	        	 }
                pagingHtml.append(i);
                pagingHtml.append("\">");
                pagingHtml.append(i);
                pagingHtml.append("</a></td>");
            }
            //pagingHtml.append("&nbsp;");
        }
        //pagingHtml.append("&nbsp;&nbsp;|&nbsp;&nbsp;");

       // 다음 block 페이지
        if (totalPage - startPage >= blockPage) {
       	 if (curUrl.indexOf("?") > -1) {
       		 pagingHtml.append("<td class='pagenum_next'><a href=\""+ curUrl +"&s_curr_page=" + (endPage + 1) + "\">");
       	 } else {
       		 pagingHtml.append("<td class='pagenum_next'><a href=\""+ curUrl +"?s_curr_page=" + (endPage + 1) + "\">");
       	 }
            pagingHtml.append("<img src='/images/sub/btn_next.gif' width='20' height='19' border='0' align='absmiddle' />");
            pagingHtml.append("</a></td>");
        }
        pagingHtml.append("</tr>\n</table>");

        //vo.setTotPage((int)((totalCount-1)/blockCount) + 1);

        return pagingHtml.toString();
    }

}
